package com.xywy.common.widget;

import android.app.AlertDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.Toast;

import com.xywy.R;
import com.xywy.common.net.NetUtil;

/**
 * Created by wei heling on 2014/6/19. 自定义的进度条
 */
public class MyProgress {

	private ImageView image; // 转动的图片
	private Animation anim; // 旋转动画
	private AlertDialog dialog; // 动画的承载框
	private Context context;
	private long sleepTime = 10000; // 默认加载时长
	private int sleep = 0; // 1:默认加载最长时间不超过10秒

	public MyProgress(Context context, int sleep) {
		this.context = context;
		this.sleep = sleep;
	}

	/**
	 * 动画开始方法
	 */
	public void start() {
		dialog = new AlertDialog.Builder(context).create();
		if (!NetUtil.hasNetwork(context)) {
			Toast.makeText(context, "暂无网络连接", Toast.LENGTH_SHORT).show();
			return;
		}
		dialog.show();
		dialog.setCanceledOnTouchOutside(false);
		Window window = dialog.getWindow();
		View view = LayoutInflater.from(context).inflate(
				R.layout.common_progress, null);
		window.setContentView(view);
		image = (ImageView) view.findViewById(R.id.image);
		anim = AnimationUtils.loadAnimation(context, R.anim.progress_rotate);
		LinearInterpolator lir = new LinearInterpolator();
		anim.setInterpolator(lir); // 设置匀速转动 但是效果并不太理想
		image.startAnimation(anim);
		new Thread() {
			@Override
			public void run() {
				try {
					if (sleep == 1) {
						sleep(sleepTime);
						dialog.dismiss();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				super.run();
			}
		}.start();
	}

	/**
	 * 动画结束方法
	 */
	public void stop() {
		if (dialog != null && dialog.isShowing())
			dialog.dismiss();
	}

}
